package com.dex4d.ui.demo;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.dex4d.R;
import com.dex4d.constants.AppConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.CustomApplication;
import com.dex4d.core.ITabFragment;
import com.dex4d.event.ExitEvent;
import com.dex4d.ui.dapp.AndroidBug5497Workaround;
import com.dex4d.ui.dapp.DappBrowserFragment;
import com.dex4d.ui.dapp.model.DappEvent;
import com.dex4d.ui.dapp.model.History;
import com.dex4d.ui.mine.fragment.TabMineFragment;
import com.dex4d.ui.qr.EasyAuthActivity;
import com.dex4d.ui.qr.EasyCaptureActivity;
import com.dex4d.ui.wallet.activity.WalletSendActivity;
import com.dex4d.ui.wallet.fragment.TabWalletFragment;
import com.dex4d.update.UpdateUtil;
import com.dex4d.utils.Log;
import com.dex4d.widgets.tab.TabLayout;
import com.framework.util.DisplayUtil;
import com.king.zxing.Intents;
import com.wallet.web3.entity.Web3Transaction;

import org.greenrobot.eventbus.EventBus;
import org.web3j.crypto.WalletUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

/**
 * Created by chengyuchun on 2017/3/7.
 * <p>
 * Dex4D 项目因为赶进度将使用MVC架构，后期如果项目复杂度增加，代码量过大，可以轻松切换至MVP架构
 * <p>
 * Activity继承 BaseActivityPresenter 既可切换至MVP开发模式，具体参考DEMO
 */
public class HomeActivity extends AppToolBarBaseActivity implements TabLayout.OnTabClickListener
        , EasyPermissions.PermissionCallbacks
        , EasyPermissions.RationaleCallbacks {
    private ITabFragment mTabFragment;

    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;

    @BindView(R.id.toolbar_right_img)
    ImageView toolbar_right_img;

    UpdateUtil appUpdate;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tab;
    }

    private long mExitTime;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, HomeActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            setStatusBarBlack();
//        }
        ArrayList<TabLayout.Tab> tabs = new ArrayList<>();
        tabs.add(new TabLayout.Tab(R.drawable.selector_tab_main, R.string.home_tab_main, com.dex4d.ui.main.fragment.TabMainFragment.class));
        tabs.add(new TabLayout.Tab(R.drawable.selector_tab_wallet, R.string.home_tab_wallet, TabWalletFragment.class));
        tabs.add(new TabLayout.Tab(R.drawable.selector_tab_browser, R.string.home_tab_browser, DappBrowserFragment.class));
        tabs.add(new TabLayout.Tab(R.drawable.selector_tab_me, R.string.home_tab_me, TabMineFragment.class));

        setTabs(tabs, this);

        AndroidBug5497Workaround.assistActivity(this, DisplayUtil.dip2px(this, 50));

    }

    @Override
    protected void initToolbar() {
        toolbar_right_img.setVisibility(View.VISIBLE);
        toolbar_right_img.setImageResource(R.drawable.home_img_scan);
    }

    @Override
    public void initVariables() {

    }

    @Override
    public void loadData() {
        appUpdate = new UpdateUtil(this);
        appUpdate.update();
    }

    @Override
    public void onTabClick(TabLayout.Tab tab) {

        try {
            ITabFragment tmpFragment = (ITabFragment) getSupportFragmentManager().findFragmentByTag(tab.targetFragmentClz.getSimpleName());
            if (tmpFragment == null) {
                tmpFragment = tab.targetFragmentClz.newInstance();
                if (mTabFragment == null) {
                    getSupportFragmentManager().beginTransaction()
                            .add(R.id.mFragmentContainerLayout, tmpFragment.getFragment(), tab.targetFragmentClz.getSimpleName())
                            .commit();
                } else {
                    getSupportFragmentManager().beginTransaction()
                            .hide(mTabFragment.getFragment())
                            .add(R.id.mFragmentContainerLayout, tmpFragment.getFragment(), tab.targetFragmentClz.getSimpleName())
                            .commit();
                }
            } else {
                getSupportFragmentManager().beginTransaction()
                        .hide(mTabFragment.getFragment())
                        .show(tmpFragment.getFragment())
                        .commit();
            }
            mTabFragment = tmpFragment;

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int index = intent.getIntExtra(AppConstants.INDEX, AppConstants.TAB_HOME);
        setCurrentPage(index);
    }

    public static void goBackToMain(Context c) {
        goBackToMain(c, AppConstants.TAB_HOME, true);
    }

    public static void goBackToMain(Context c, int pageCode) {
        goBackToMain(c, pageCode, false);
    }

    public static void goBackToMain(Context c, int pageCode, boolean logout) {
        if (logout) {

        }
        Intent intent = new Intent(c, HomeActivity.class);
        intent.putExtra(AppConstants.INDEX, pageCode);
        c.startActivity(intent);
    }

    public void setTabs(ArrayList arrayList, TabLayout.OnTabClickListener onTabClickListener) {
        mTabLayout.setUpData(arrayList, onTabClickListener);
        mTabLayout.setCurrentTab(0);
    }

    private void setCurrentPage(int pageCode) {
        mTabLayout.setCurrentTab(pageCode);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, getResources().getString(R.string.system_exit), Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            CustomApplication.getClient().tearDown();
            EventBus.getDefault().post(new ExitEvent());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    System.exit(0);
                }
            }, 500);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public static final int REQUEST_CODE_SCAN = 0X01;
    public static final int REQUEST_CODE_CAMERA = 0X02;
    public static final int REQUEST_CODE_DAPP = 0X03;
    public static final int REQUEST_CODE_DAPP_WEB = 0X05;

    @AfterPermissionGranted(REQUEST_CODE_CAMERA)
    @OnClick(R.id.toolbar_right_img)
    public void scan() {
        if (hasCameraPermission()) {
            // Have permission, do the thing!
            EasyCaptureActivity.start(this);
        } else {
            // Ask for one permission
//            EasyPermissions.requestPermissions(
//                    this,
//                    getString(R.string.rationale_camera),
//                    REQUEST_CODE_CAMERA,
//                    Manifest.permission.CAMERA);

            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, REQUEST_CODE_CAMERA, Manifest.permission.CAMERA)
                            .setRationale(R.string.rationale_camera)
                            .setPositiveButtonText(R.string.rationale_ask_ok)
                            .setNegativeButtonText(R.string.rationale_ask_cancel)
                            .setTheme(R.style.Theme_AppCompat)
                            .build());
        }
    }

    private boolean hasCameraPermission() {
        return EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == REQUEST_CODE_SCAN) {//扫码
                String result = data.getStringExtra(Intents.Scan.RESULT);
                if (TextUtils.isEmpty(result)) return;

                if (WalletUtils.isValidAddress(result)) {//跳转到转账页面
                    WalletSendActivity.start(this, result);
                } else {
                    EasyAuthActivity.start(this, result);
                }
            } else if (requestCode == REQUEST_CODE_DAPP) {
                //处理
                if (resultCode == RESULT_OK) {
                    Web3Transaction transaction = data.getParcelableExtra("TX");
                    DappEvent dappEvent = new DappEvent(transaction, data.getBooleanExtra("SIGNED",true));
                    EventBus.getDefault().post(dappEvent);
                }
            }else if (requestCode == REQUEST_CODE_DAPP_WEB) {
                //处理
                if (resultCode == RESULT_OK) {
                    History history = data.getParcelableExtra("history");
                    EventBus.getDefault().post(history);
                }
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been granted

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been denied

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        Log.i("onRationaleAccepted:" + requestCode);
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        Log.i("onRationaleDenied:" + requestCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        appUpdate.cancel();
    }
}
